package org.xc.uvc_camera;

import android.os.Environment;
import android.text.TextUtils;

import com.liulishuo.okdownload.DownloadListener;
import com.liulishuo.okdownload.DownloadTask;

import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class FileUtil {

    public static final String BASE_PATH = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator  + "666";

    static {
        File rootFile = new File(BASE_PATH);
        if (!rootFile.exists()) {
            rootFile.mkdirs();
        }
    }

    public static String createFile(String fileName) {
        File file = new  File(BASE_PATH,fileName);
        if (file.exists()) {
            file.delete();
        }
        try {
            file.createNewFile();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return file.getAbsolutePath();
    }

    public static File getFile(String fileName) {
        if (TextUtils.isEmpty(fileName)) {
            return null;
        }
        File file = new File(BASE_PATH,fileName);
        if (!file.exists()) {
            return null;
        }
        return file;
    }

    /**
     * type 7-前七 8-后八
     */
    public static List<File> getFiles(String currFileName,int type) {
        File rootFile = new File(BASE_PATH);
        File[] mp4Files = rootFile.listFiles(new FilenameFilter() {
            @Override
            public boolean accept(File file, String s) {
                return s.endsWith("mp4");
            }
        });

        //当前文件时间戳
        long curr = Long.valueOf(currFileName);
        List<File> files = new ArrayList<>();
        for(File file: mp4Files) {
            long temp = Long.valueOf(file.getName().split("\\.")[0]);

            //实际上每个视频文件不会恰好间隔60s，这里搞个65s
            long flag = type == 7 ? Constant.QI :Constant.BA;
            if (type == 7) {
                //前七
                if (curr - temp <= flag && curr - temp >= 0) {
                    files.add(file);
                }
            } else if (type == 8) {
                //后八
                if (temp - curr <= flag && temp - curr >= 0) {
                    files.add(file);
                }
            }
        }
        return files;
    }

    public static DownloadTask download(String url, File file, DownloadListener listener) {
        DownloadTask task = new DownloadTask.Builder(url,file)
                .setMinIntervalMillisCallbackProcess(30)
                .setPassIfAlreadyCompleted(false)
                .build();
        task.enqueue(listener);
        return task;
    }
}
